using System;
using System.Collections.Generic;

namespace Mbs
{
    public interface ICompositeDisposableObject:IDisposable
    {
        void Add(IDisposable item);
    }

    [Serializable]
    public class CompositeDisposableObject : DisposableObject, ICompositeDisposableObject
    {
        private readonly Stack<WeakReference> Items;
        public CompositeDisposableObject()
        {
            Items = new Stack<WeakReference>();
        }


        public CompositeDisposableObject(int capacity)
        {

            Items = new Stack<WeakReference>(capacity);
        }

        public void Add(IDisposable item)
        {
            CheckNotDisposed();
            
            if (item != null)
                Items.Push(new WeakReference(item));
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                while (Items.Count > 0)
                {
                    WeakReference reference = Items.Pop();
                    IDisposable item = (IDisposable)reference.Target;
                    if (reference.IsAlive)
                        item.Dispose();
                }
            }
        }
    }
}
